package red.mlz.app.crond;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import red.mlz.module.module.sms.entity.Sms;
import red.mlz.module.module.sms.entity.SmsCrond;
import red.mlz.module.module.sms.service.SmsService;
import red.mlz.module.utils.BaseUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SmsSendCrond {

    @Autowired
    private SmsService smsService;

    /**
     * 每分钟执行一次（整分钟触发）
     */
    @Scheduled(cron = "0 * * * * ?")
    public void doSendSms() {
        long startTime = System.currentTimeMillis();
        log.info("[定时任务] 开始执行扫描...");
        try {
            // 这里替换为实际的扫描逻辑
            doScan();
            log.info("[定时任务] 扫描完成 | 耗时: {}ms",
                    System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("[定时任务] 执行异常", e);
        }
    }

    private void doScan() {
        List<SmsCrond> smsCrondList = smsService.findNoSendSms();
        if (!BaseUtils.isEmpty(smsCrondList)) {
            List<Sms> smsList = new ArrayList<>();
            for (SmsCrond smsCrond : smsCrondList) {
                Sms sms = smsService.crondSend(smsCrond.getPhone(), smsCrond.getContent());
                if (sms.getResult().equals("success")){
                    smsCrond.setStatus(1);
                }else {
                    smsCrond.setStatus(2);
                }
                smsList.add(sms);
            }
            smsService.insertBatch(smsList);
            smsService.updateSmsCrondBatch(smsCrondList);
        }
    }

}
